package com.gowhere.service.impl.system;

import com.github.pagehelper.PageHelper;
import com.gowhere.domain.Permission;
import com.gowhere.domain.Role;
import com.gowhere.mapper.system.RoleMapper;
import com.gowhere.service.system.RoleService;
import com.gowhere.utils.MapperUtil;
import com.gowhere.utils.UidUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.Map;

public class RoleServiceImpl implements RoleService {
    //带分页查询
    @Override
    public List<Role> findByPage(int pageNum, int pageSize) {
        //获取session对象
        SqlSession session = MapperUtil.getSession();
        //获取处理对象
        RoleMapper mapper = session.getMapper(RoleMapper.class);
        PageHelper.startPage(pageNum, pageSize);
        //执行操作
        List<Role> list = mapper.findByPage();
        //释放资源
        MapperUtil.close(session);
        System.out.println(list);
        //返回结果集
        return list;
    }

    @Override
    public void save(Role role) {
        //生成id
        String uid = UidUtil.getUid();
        role.setId(uid);
        //1获取session
        SqlSession session = MapperUtil.getSession();
        //2获取代理对象
        RoleMapper mapper = session.getMapper(RoleMapper.class);
        //3执行操作
        mapper.save(role);
        //4释放资源
        MapperUtil.close(session);
    }

    @Override
    public void delete(String ids) {
        //获取session对象
        SqlSession session = MapperUtil.getSession();
        //获取代理对象
        RoleMapper mapper = session.getMapper(RoleMapper.class);
        //执行操作
       if (ids!=null){
           for (String id : ids.split(",")) {
              mapper.delete(id);
           }
       }
        //释放资源
        MapperUtil.close(session);
    }

    @Override
    public Role findById(String id) {
        SqlSession session = MapperUtil.getSession();
        RoleMapper mapper = session.getMapper(RoleMapper.class);
       Role role= mapper.findById(id);
        MapperUtil.close(session);
        return role;
    }

    @Override
    public List<Map> findRolePmByRid(String roleId) {
        SqlSession sqlSession = MapperUtil.getSession();
        RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);
        List<Map> roleList = mapper.findRolePmByRid(roleId);
        MapperUtil.close(sqlSession);
        return roleList;

    }

    @Override
    public void updateRolePm(String roleId, String permissions) {
        SqlSession sqlSession = MapperUtil.getSession();
        RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);

        mapper.deleteRolePm(roleId);

        if (StringUtils.isNotBlank(permissions)) {
            String[] mids = permissions.split(",");
            for (String moduleId : mids) {
                mapper.addRolePm(roleId, moduleId);
            }
        }
        MapperUtil.close(sqlSession);

    }
}
